<template>
  <div class="user-profile">
    <el-card class="card">
      <template #header>
        <div class="card-header">
          <el-avatar
            :src="user.url || defaultAvatar"
            size="large"
            shape="circle"
          />
          <div class="user-info">
            <h2>{{ user.userName }}</h2>
            <p>ID：{{ user.userId }}</p>
            <p>邮箱：{{ user.email || "未绑定" }}</p>
          </div>
          <el-button
            type="success"
            size="small"
            @click="openEditDialog"
            style="margin-left: auto"
          >
            编辑个人信息
          </el-button>
          <el-button type="success" size="small" @click="goToGameView"
            >前往娱乐娱乐吧！</el-button
          >
        </div>
      </template>

      <el-descriptions title="用户信息" border column="1">
        <el-descriptions-item label="用户名">{{
          user.userName
        }}</el-descriptions-item>
        <el-descriptions-item label="ID">{{
          user.userId
        }}</el-descriptions-item>
        <el-descriptions-item label="角色">{{
          user.userSystemRole || "普通用户"
        }}</el-descriptions-item>
        <el-descriptions-item label="注册时间">{{
          user.createTime || "未知"
        }}</el-descriptions-item>
      </el-descriptions>

      <el-button type="primary" @click="goToBlog" class="mt-4"
        >博客中心</el-button
      >
      <el-button
        v-if="user.userSystemRole === 'admin'"
        type="primary"
        @click="goToSubjectManager"
        class="mt-4"
      >
        学科管理
      </el-button>

      <el-button
        v-if="user.userSystemRole === 'admin'"
        type="primary"
        @click="goToUserManager"
        class="mt-4"
      >
        用户管理
      </el-button>

      <el-button type="primary" @click="goToRedirectPage" class="mt-4"
        >返回登录中心</el-button
      >
    </el-card>

    <!-- 编辑个人信息弹窗 -->
    <el-dialog
      title="编辑个人信息"
      v-model="editDialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        :model="editUser"
        :rules="rules"
        ref="editForm"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="editUser.userName" autocomplete="off" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUser.email" autocomplete="off" />
        </el-form-item>

        <el-form-item label="新密码" prop="passWord">
          <el-input
            v-model="editUser.passWord"
            type="passWord"
            autocomplete="new-passWord"
            placeholder="留空则不修改密码"
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassWord">
          <el-input
            v-model="editUser.confirmPassWord"
            type="passWord"
            autocomplete="new-passWord"
            placeholder="请再次输入新密码"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submitEdit"
          >保存</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { getUserProfile, updateUserProfile } from "../api/userProfiles.js";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";

const router = useRouter();
const user = ref({});
const editDialogVisible = ref(false);
const editForm = ref(null);
const loading = ref(false);

const goToSubjectManager = () => {
  router.push("/api/subject/subjects"); // 注意：这里是前端路由路径，不是接口路径
};
const goToUserManager = () => {
  router.push("/api/user/users"); // 注意：这里是前端路由路径，不是接口路径
};

// 根据角色跳转到对应中心
const goToRedirectPage = () => {
  const role = user.value.userSystemRole;
  switch (role) {
    case "student":
      router.push("/api/user/StudentRedirectPage");
      break;
    case "teacher":
      router.push("/api/user/TeacherRedirectPage");
      break;
    case "admin":
      router.push("/api/user/AdminRedirectPage");
      break;
    default:
      ElMessage.warning("未知角色，已返回默认登录页面");
      router.push("/login");
  }
};

const goToGameView = () => {
  router.push("/api/game");
};

const goToBlog = () => {
  router.push("/api/blogs");
};

// 表单数据
const editUser = reactive({
  userName: "",
  email: "",
  passWord: "",
  confirmPassWord: "",
});

// 表单校验规则
const rules = {
  userName: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  email: [
    { type: "email", message: "邮箱格式不正确", trigger: ["blur", "change"] },
  ],
  passWord: [{ min: 6, message: "密码至少6位", trigger: "blur" }],
  confirmPassWord: [
    {
      validator: (rule, value, callback) => {
        if (editUser.passWord && value !== editUser.passWord) {
          callback(new Error("两次输入密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

// 加载当前用户信息
const loadUserInfo = async () => {
  try {
    const res = await getUserProfile();
    user.value = res.data || {};
    initEditForm();
  } catch {
    ElMessage.error("获取用户信息失败");
  }
};

// 初始化编辑表单
function initEditForm() {
  editUser.userName = user.value.userName || "";
  editUser.email = user.value.email || "";
  editUser.passWord = "";
  editUser.confirmPassWord = "";
  if (editForm.value) editForm.value.clearValidate();
}

// 打开编辑弹窗
const openEditDialog = () => {
  initEditForm();
  editDialogVisible.value = true;
};

// 重置表单
const resetForm = () => {
  initEditForm();
};

// 提交修改
const submitEdit = () => {
  if (!editForm.value) return;
  editForm.value.validate(async (valid) => {
    if (!valid) return;

    loading.value = true;
    try {
      const payload = {
        userName: editUser.userName,
        email: editUser.email,
      };
      if (editUser.passWord) {
        payload.passWord = editUser.passWord;
      }

      await updateUserProfile(payload);
      ElMessage.success("更新成功");
      editDialogVisible.value = false;
      await loadUserInfo();
    } catch {
      ElMessage.error("更新失败");
    } finally {
      loading.value = false;
    }
  });
};

router.beforeEach((to, from, next) => {
  const role = localStorage.getItem("userSystemRole"); // 这里取你实际的用户角色
  if (to.meta.role && to.meta.role !== role) {
    ElMessage.error("没有权限访问该页面");
    return next("/login");
  }
  next();
});

onMounted(() => {
  loadUserInfo();
});
</script>


<style scoped>
.user-profile {
  padding: 40px;
  display: flex;
  justify-content: center;
}

.card {
  max-width: 600px;
  width: 100%;
  border-radius: 12px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-info h2 {
  margin: 0;
  font-size: 20px;
}
.user-info p {
  margin: 4px 0;
  color: #666;
}
.mt-4 {
  margin-top: 16px;
}
</style>
